﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Chire.ChireInter.Class;
using Chire.ChireInter.Motto;
using Chire.ChireInter.Order;
using Chire.ChireInter.Parent;
using Chire.ChireInter.Sign;
using Chire.ChireInter.Students;
using Chire.ChireInter.Teacher;
using Chire.wechat;
using Chire.ChireInter.Event_calendar;

namespace Chire.ChireInter.Task
{
    #region 每天早上7点提醒
    public class Task_EveryDay
    {
        #region 0.主方法
        public void mainManager()
        {
            // 1. 获取当天的事件
            Event_Action eventAction = new Event_Action();
            Class_Action classAction = new Class_Action();
            Student_Action studentAction = new Student_Action();
            Sign_Action signAction = new Sign_Action();
            List<Event_Model> currentDayeventList = eventAction.getEventList(DateTime.Now.Date.ToString());
            // 2.根据所有的事件获取当前的课程id
            List<Class_Model> classList = new List<Class_Model>();
            for (int i = 0; i < currentDayeventList.Count; i++) {
                Event_Model eventModel = currentDayeventList[i];
                // 根据classid 获取当前的班级
                Class_Model singleClassModel = classAction.getClassInfoWithId(eventModel.class_id); 
                // 1. 获取随机数
                string randomStr = Constance.Instance.getRandomStr(10);
                // 插入待上课信息
                addClassStartRember(eventModel.class_id);
                // 设置所有的学生为未签到状态
                signAction.addAllStudentSignInWithClassId(eventModel.class_id, randomStr);
                // 插入新课程信息
                signAction.addSignClassInfo(eventModel.class_id, randomStr);
                // 进行发送信息
                List<Student_Model> studentList = studentAction.getAllStudentWithClassId(eventModel.class_id);
                for (int j = 0; j < studentList.Count; j++)
                {
                    Student_Model studentModel = studentList[j];
                    sendMsgWithClassWillStart(studentModel, singleClassModel);
                }
                // 将当前是否推送的条目设置为已推送
                eventAction.wechatSettingSignPush(eventModel.id);
            }



            //// 1. 获取所有的班级
            //
            //
            //List<Class_Model> classList =  classAction.getCurrentDayHasInClass();
            //
            //// 2. 获取今天星期几
            //string weekDay = getCurrentDay();

            //// 2. 判断每个班级信息
            //for (int i = 0; i < classList.Count; i++)
            //{
            //    Class_Model classModel = classList[i];
            //    string[] weekArr = classModel.week.Split(',');
            //    if (weekArr.Contains(weekDay) == true)
            //    {            // 表示该班的人今天要发
         
            //    }
            //}
        }
        #endregion

        #region 3.获取今天星期几
        public string getCurrentDay()
        {
            string[] Day = new string[] { "0", "1", "2", "3", "4", "5", "6" };
            string week = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
            return week;
        }
        #endregion

        #region 4.发送信息
        public void sendMsgWithClassWillStart(Student_Model studentModel, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】开课提醒";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.begintime + " - " + classInfo.endtime;
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = "万豪洋服";
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = classInfo.teacher.name + classInfo.teacher.phone;
            keyword4.color = "#173177";

            Motto_Action mottoAction = new Motto_Action();
            WechatModelData remark = new WechatModelData();
            remark.value = mottoAction.getMotto();
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.remark = remark;

            wechatToken.wechatStartClassMsg(studentModel.openid, list);

        }
        #endregion

        #region 5.插入当天的开课记录
        public void addClassStartRember(string classId)
        {
            Order_Action action = new Order_Action();
            action.order_willStartGetList(classId);
        }
        #endregion
    }

    #endregion

    #region 进行上课前的1小时开课提醒 && 半小时后签退，
    public class Task_EveryClass
    {
        #region 0.主方法
        public void mainManager()
        {
            // 1. 获取所有的班级
            Class_Action classAction = new Class_Action();
            List<Class_Model> classList = classAction.getCurrentDayHasInClass();

            Student_Action studentAction = new Student_Action();
            Parent_Action parentAction = new Parent_Action();
            Sign_Action signAction = new Sign_Action();

            // 2. 获取今天星期几
            string weekDay = getCurrentDay();

            // 2. 遍历所有的班级判断班级开课时间
            for (int i = 0; i < classList.Count; i++)
            {
                Class_Model classModel = classList[i];
                string[] weekArr = classModel.week.Split(',');
                if (weekArr.Contains(weekDay) == true)             // 表示今天
                {
                    DateTime dt = Convert.ToDateTime(classModel.begintime);          // 开课时间
                    int beginHour = dt.Hour;
                    int beginMin = dt.Minute;
                    double beginMinF = beginMin * 1.0 / 60;
                    double beginMinTime = beginHour + beginMinF;


                    int currentHour = DateTime.Now.Hour;                           // 当前时间
                    int currentMin = DateTime.Now.Minute;
                    double currentMinF = currentMin * 1.0 / 60;
                    double currentMinTime = currentHour + currentMinF;

                    DateTime enddt = Convert.ToDateTime(classModel.endtime);          // 结束时间
                    int endHour = enddt.Hour;
                    int endMin = enddt.Minute;
                    double endMinF = endMin * 1.0 / 60;
                    double endMinTime = endHour + endMinF;

                    bool hasNoti_ClassStart = hasPush(classModel.id, EveryStatus.EveryStatus_ClassStart);
                    // 开课提醒【推送给学生和学生家长】
                    if (hasNoti_ClassStart == false)
                    {            // 没有推送过
                        if (currentMinTime + 1 > beginMinTime && currentMinTime > 7 && currentMinTime < 21)
                        {
                            // 2. 获取班内所有的学生
                            List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classModel.id);
                            // 2.1 给所有班级内的学生推送
                            for (int j = 0; j < studentList.Count; j++)
                            {
                                // 2.2 推送给所有学生
                                Student_Model studentModel = studentList[j];
                                sendMsgWithClassWillStart(studentModel, classModel);
                                // 2.3 推送给所有学生绑定的家长
                                List<Parent_Model> parentList = parentAction.getAllParentWithStudentId(studentModel.id);
                                for (int p = 0; p < parentList.Count; p++)
                                {
                                    Parent_Model parentModel = parentList[p];
                                    sendMsgToParentWithClassWillStart(parentModel, classModel);
                                }
                            }

                            // 2.1 订单处进行标记将要开课
                            Order_Action orderAction = new Order_Action();
                            orderAction.order_willStartGetList(classModel.id);

                            // 3.标记已经推送过
                            insertHasPushInfo(classModel.id, EveryStatus.EveryStatus_ClassStart);
                        }
                    }

                    // 课程将要结束推送
                    bool hasNoti_ClassEnd = hasPush(classModel.id, EveryStatus.EveryStatus_ClassWillEnd);
                    if (hasNoti_ClassEnd == false)
                    {       // 表示没有推送过
                        if (currentMinTime + 0.5 > endMinTime && currentMinTime > 7 && currentMinTime < 21)
                        {
                            // 2. 获取班内所有的学生
                            List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classModel.id);
                            // 2.1 给所有班级内的学生家长推送
                            for (int j = 0; j < studentList.Count; j++)
                            {
                                // 2.2 推送给所有学生
                                Student_Model studentModel = studentList[j];
                                // 2.3 推送给所有学生绑定的家长
                                List<Parent_Model> parentList = parentAction.getAllParentWithStudentId(studentModel.id);
                                for (int p = 0; p < parentList.Count; p++)
                                {
                                    Parent_Model parentModel = parentList[p];
                                    sendMsgToParentWithClasWillEnd(parentModel, classModel);
                                }
                            }
                            // 3.标记已经推送过
                            insertHasPushInfo(classModel.id, EveryStatus.EveryStatus_ClassWillEnd);
                        }
                    }

                    // 课程结束10分钟之内没签退
                    // 1. 表示课程结束后，10分钟后签退没推送过
                    bool hasNoti_ClassEndNotSignOut = hasPush(classModel.id, EveryStatus.EveryStatus_NotSignOut);
                    // 2.判断学生有没有签退
                    double tenMinTime = 10 * 1.0 / 60;
                    if (hasNoti_ClassEndNotSignOut == false && currentMinTime > endMinTime + tenMinTime)
                    {
                        // 2. 获取班内所有的学生
                        List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classModel.id);
                        // 2.1 给所有班级内的学生家长推送
                        for (int j = 0; j < studentList.Count; j++)
                        {
                            // 2.2 推送给所有学生
                            Student_Model studentModel = studentList[j];
                            if (signAction.signHasSignOut(studentModel.id, classModel.id) == false)
                            {
                                // 进行推送
                                sendMsgToWaringSignOut(studentModel, classModel);
                            }
                        }
                        // 3.标记已经推送过
                        insertHasPushInfo(classModel.id, EveryStatus.EveryStatus_NotSignOut);
                    }

                    // 课程开始10分钟后没签到
                    // 1. 表示课程开始后，10分钟没推送过
                    bool hasNoti_ClassStartNotSignIn = hasPush(classModel.id, EveryStatus.EveryStatus_NotSignIn);
                    if (hasNoti_ClassStartNotSignIn == false && currentMinTime > beginMinTime + tenMinTime)
                    {
                        // 2. 获取班内所有的学生
                        List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classModel.id);
                        // 2.1 给所有班级内的学生家长推送
                        for (int j = 0; j < studentList.Count; j++)
                        {
                            // 2.2 推送给所有学生
                            Student_Model studentModel = studentList[j];
                            if (signAction.signHasSignIn(studentModel.id, classModel.id) == false)
                            {
                                // 进行推送
                                sendMsgToWaringClassStartNotSign(studentModel, classModel);
                            }
                        }
                        // 3.标记已经推送过
                        insertHasPushInfo(classModel.id, EveryStatus.EveryStatus_NotSignIn);
                    }
                }
            }
        }
        #endregion

        public enum EveryStatus
        {
            EveryStatus_ClassStart = 2,              // 开课提醒
            EveryStatus_NotSignIn = 3,               // 时间到了没签到
            EveryStatus_NotSignOut = 5,             // 没签退
            EveryStatus_ClassWillEnd = 6,            // 课程将要结束
        }


        #region 5.判断是否 开课提醒已经推送过
        public bool hasPush(string classid, EveryStatus status)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select top 1 * from wechat_notif where class_id = '" + classid + "' and date = '" + DateTime.Now.ToShortDateString() + "' and type = '" + (int)status + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            bool hasPush = false;
            if (dr.Read())
            {
                hasPush = true;
            }
            sqlcon.Close();
            return hasPush;
        }
        #endregion

        #region 插入推送信息
        public void insertHasPushInfo(string class_id, EveryStatus status)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into wechat_notif(class_id,date,time,type) values (@class_id,@date,@time,@type)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值


            // 1. 作者id
            cmd.Parameters.Add("@class_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@class_id"].Value = class_id;
            // 1. 日记标题
            cmd.Parameters.Add("@date", SqlDbType.VarChar, 20);
            cmd.Parameters["@date"].Value = DateTime.Now.ToShortDateString();
            // 2.日记详情
            cmd.Parameters.Add("@time", SqlDbType.VarChar, 20);
            cmd.Parameters["@time"].Value = DateTime.Now.ToShortTimeString();

            cmd.Parameters.Add("@type", SqlDbType.Int, 2);
            cmd.Parameters["@type"].Value = (int)status;

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 3.获取今天星期几
        public string getCurrentDay()
        {
            string[] Day = new string[] { "0", "1", "2", "3", "4", "5", "6" };
            string week = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
            return week;
        }
        #endregion

        #region 4.发送信息
        public void sendMsgWithClassWillStart(Student_Model studentModel, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】开课提醒，您的课程将于1小时后开课。为了最好的上课效果，请提前做好准备。";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.begintime + " - " + classInfo.endtime;
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = "万豪洋服";
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = classInfo.teacher.name + classInfo.teacher.phone;
            keyword4.color = "#173177";

            Motto_Action mottoAction = new Motto_Action();
            WechatModelData remark = new WechatModelData();
            remark.value = mottoAction.getMotto();
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.remark = remark;

            wechatToken.wechatStartClassMsg(studentModel.openid, list);

        }
        #endregion

        #region 5. 给家长进行推送
        // 课程1小时后将要开始
        public void sendMsgToParentWithClassWillStart(Parent_Model parent, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】上课提醒";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.begintime + " - " + classInfo.endtime;
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = "万豪洋服";
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = classInfo.teacher.name + classInfo.teacher.phone;
            keyword4.color = "#173177";

            Motto_Action mottoAction = new Motto_Action();
            WechatModelData remark = new WechatModelData();
            remark.value = "您孩子的课程将于1小时后开课。为了最好的上课效果，请提前做好准备。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.remark = remark;

            wechatToken.wechatStartClassMsg(parent.openid, list);
        }

        // 课程1小时后将要结束
        public void sendMsgToParentWithClasWillEnd(Parent_Model parent, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "【炽热教育】下课提醒";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.teacher.name + classInfo.teacher.phone;
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = classInfo.endtime;
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = "万豪洋服";
            keyword4.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = "您的孩子将于半小时后下课，如有接送，请提前准备，谢谢。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.remark = remark;

            wechatToken.wechatWillEndClassMsg(parent.openid, list);
        }

        // 课程结束但是没有签退，提醒签退
        public void sendMsgToWaringSignOut(Student_Model studentModel, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = studentModel.name + "," + "课程结束已经10分钟了，还没签退哦，抓紧签退吧。";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.endtime;
            keyword2.color = "#173177";


            WechatModelData remark = new WechatModelData();
            remark.value = "课程已结束，你还是挺棒的，加油！";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.remark = remark;

            wechatToken.wechatClassEndWaringSignOut(studentModel.openid, list);
        }

        // 课程已经开课，但是没有签到
        public void sendMsgToWaringClassStartNotSign(Student_Model studentModel, Class_Model classInfo)
        {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = studentModel.name + "," + "课程已经开始10分钟了，还没签到哦，抓紧签到吧。（如已请假请忽略）";
            first.color = "#FF0000";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = classInfo.name;
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = classInfo.begintime;
            keyword2.color = "#173177";


            WechatModelData remark = new WechatModelData();
            Motto_Action mottoAction = new Motto_Action();

            remark.value = mottoAction.getMotto();
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.remark = remark;

            wechatToken.wechatClassStartNotSignIn(studentModel.openid, list);
        }
        #endregion


    }
    #endregion

    #region 每天晚上5点进行同步事件
    public class Task_EveryDayNight
    {
        #region 0.主方法
        public void mainManager()
        {
            // 1. 获取所有事件列表判断是否有未推送的信息
            Event_Action eventAction = new Event_Action();
            List<Event_Model> eventList = eventAction.getEventListWithNotPush();
            // 2. 这些列表进行推送
            for (int i = 0; i < eventList.Count; i++)
            {
                Event_Model eventModel = eventList[i];
                // 事件时间戳转换成时间
                DateTime dat = Constance.ConvertLongToDateTime(eventModel.timeInterval);
                string timeStr = dat.ToString("yyyy-MM-dd HH:mm");

                // 3. 获取事件下的所有学生
                List<Event_Student> eventStudentList = eventAction.getEventStudentList(eventModel.id);
                for (int j = 0; j < eventStudentList.Count; j++)
                {
                    Event_Student eventStudent = eventStudentList[j];
                    eventAction.WechatPushEventManager(eventStudent.userId, eventStudent.student.name, eventModel.classModel.name, timeStr);
                }
                // 将该内容转为已推送
                eventAction.wechatSettingSignPush(eventModel.id);
            }
        }
        #endregion
    }
    #endregion

    #region 每周日进行下周的事件同步添加
    public class Task_EveryEventWeekDay
    {
        // 1. 
        public void mainManager()
        {
            getAllClassManager();
        }

        // 2. 
        public void getAllClassManager()
        {
            Event_Action eventAction = new Event_Action();

            // 1. 获取所有班级
            Class_Action classAction = new Class_Action();
            List<Class_Model> classList = classAction.classGetAllClass();

            // 2. 获取当前周几
            string weekDay = getCurrentDay(DateTime.Now);

            // 获取每周开始日期时间戳
            DateTime weekStartDateTime = Constance.WeekStartTime;
            long currentTimeInt = Constance.Instance.ConvertDateTimeInt(weekStartDateTime);
            // 获取本周结束日时间戳
            DateTime weekEndDateTime = Constance.WeekEndTime;
            long endTimeInt = Constance.Instance.ConvertDateTimeInt(weekEndDateTime);
            // 1. 判断是否插入过数据
            bool hasEventInsert = eventAction.eventWeekHas(currentTimeInt, endTimeInt);
            if (hasEventInsert == false)
            {
                for (int i = 0; i < classList.Count; i++)
                {
                    Class_Model classModel = classList[i];
                    // 获取本课程的开课周期
                    List<Class_Time_Model> classTimeArr = classModel.classtimelist;

                    // 2. 我该课程的开课时间进行循环
                    for (int wt = 0; wt < classTimeArr.Count; wt++) { 
                        // 1. 获取当前的timeModel
                        Class_Time_Model singleClassTimeModel = classTimeArr[wt];
                        // 2. 根据当前时间进行插入事件
                        long dayTimeInt = Convert.ToInt32(singleClassTimeModel.week) * 24 * 3600;
                        // 获取每天的时间戳
                        long everyTimeInt = dayTimeInt + currentTimeInt;
                        // 时间戳转为日期
                        DateTime dayTime = Constance.ConvertLongToDateTime(everyTimeInt);

                        //拼接课程时间
                        string dayTimeStr = dayTime.ToString();
                        string[] dayTimeStr1 = dayTimeStr.Split(' ');
                        string dayTimeStr2 = dayTimeStr1[0];

                        string dayTimeStr3 = dayTimeStr2 + " " + singleClassTimeModel.begintime;
                        DateTime dayTime4 = Convert.ToDateTime(dayTimeStr3);
                        string dayTime5 = dayTime4.ToString();

                        // 进行插入事件
                        string eventId = eventAction.addEventManager(classModel.name, dayTime5, classModel.id, EventType.EventTypeClass);

                        // 根据班级获取所有学生
                        Student_Action studentAction = new Student_Action();
                        List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classModel.id);
                        // 根据学生将事件按数据插入到表中
                        for (int s = 0; s < studentList.Count; s++)
                        {
                            Student_Model student = studentList[s];
                            eventAction.addEventWithStudent(student.id, eventId);
                        }
                    }
                      
                }
                // 插入记录数据
                eventAction.eventWeekAdd(currentTimeInt, endTimeInt);
            }
        }

        #region 3.获取今天星期几
        public string getCurrentDay(DateTime time)
        {
            string[] Day = new string[] { "0", "1", "2", "3", "4", "5", "6" };
            string week = Day[Convert.ToInt32(time.DayOfWeek.ToString("d"))].ToString();
            return week;
        }
        #endregion
    }
    #endregion
}